import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:hiot_cloud_app_v1/app/data/models/device_model.dart';
import 'package:hiot_cloud_app_v1/app/data/providers/device_provider.dart';
import 'package:hiot_cloud_app_v1/app/routes/app_pages.dart';
import 'package:hiot_cloud_app_v1/app/services/snackbar_service.dart';
import 'package:hiot_cloud_app_v1/app/constants/enums/device_type.dart';

/// 添加设备控制器
class AddDeviceController extends GetxController {
  // 基础依赖
  final DeviceProvider _deviceProvider = Get.find<DeviceProvider>();
  final SnackbarService _snackbarService = Get.find<SnackbarService>();
  
  // 步骤控制
  final RxInt currentStep = 0.obs;
  
  // 设备扫描相关
  final RxBool isScanning = false.obs;
  final RxList<DeviceModel> discoveredDevices = <DeviceModel>[].obs;
  
  // 设备信息相关
  final RxString deviceId = ''.obs;
  final RxString deviceName = ''.obs;
  final RxString deviceType = ''.obs;
  final RxString deviceIp = ''.obs;
  
  // 设备分组相关
  final RxList<String> deviceGroups = <String>['默认分组', '客厅', '卧室', '厨房', '浴室'].obs;
  final RxString deviceGroup = '默认分组'.obs;
  
  // 高级配置
  final RxBool isAdvancedConfig = false.obs;
  
  @override
  void onInit() {
    super.onInit();
  }

  @override
  void onClose() {
    super.onClose();
  }
  
  /// 扫描设备
  void scanDevices() {
    if (isScanning.value) return;
    
    isScanning.value = true;
    discoveredDevices.clear();
    
    // 模拟设备发现过程
    Future.delayed(const Duration(seconds: 2), () {
      // 添加模拟设备
      discoveredDevices.addAll([
        DeviceModel(
          id: 'dev001',
          name: '智能灯-客厅',
          type: DeviceType.lightingController,
          status: DeviceStatus.offline,
          createdAt: DateTime.now(),
          lastUpdatedAt: DateTime.now(),
          ownerId: 'user001',
          isEnabled: true,
          isShared: false,
        ),
        DeviceModel(
          id: 'dev002',
          name: '温湿度传感器-卧室',
          type: DeviceType.temperatureSensor,
          status: DeviceStatus.online,
          createdAt: DateTime.now(),
          lastUpdatedAt: DateTime.now(),
          ownerId: 'user001',
          isEnabled: true,
          isShared: false,
        ),
      ]);
      
      isScanning.value = false;
    });
  }
  
  /// 停止扫描
  void stopScan() {
    isScanning.value = false;
  }
  
  /// 选择设备
  void selectDevice(DeviceModel device) {
    deviceId.value = device.id;
    deviceName.value = device.name;
    deviceType.value = device.type.toReadableString();
    deviceIp.value = device.ipAddress ?? '未知';
    
    // 切换到下一步
    nextStep();
  }
  
  /// 下一步
  void nextStep() {
    if (currentStep.value < 2) {
      currentStep.value++;
    }
  }
  
  /// 上一步
  void previousStep() {
    if (currentStep.value > 0) {
      currentStep.value--;
    }
  }
  
  /// 更新设备名称
  void updateDeviceName(String name) {
    deviceName.value = name;
  }
  
  /// 更新设备分组
  void updateDeviceGroup(String group) {
    deviceGroup.value = group;
  }
  
  /// 添加设备分组
  void addDeviceGroup(String newGroup) {
    if (!deviceGroups.contains(newGroup) && newGroup.isNotEmpty) {
      deviceGroups.add(newGroup);
      deviceGroup.value = newGroup;
    }
  }
  
  /// 切换高级配置
  void toggleAdvancedConfig() {
    isAdvancedConfig.value = !isAdvancedConfig.value;
  }
  
  /// 添加设备
  void addDevice() async {
    if (deviceName.value.isEmpty) {
      _snackbarService.showError('请输入设备名称');
      return;
    }
    
    if (deviceType.value.isEmpty) {
      _snackbarService.showError('请选择设备类型');
      return;
    }
    
    try {
      // 显示加载指示器
      Get.dialog(
        const Center(child: CircularProgressIndicator()),
        barrierDismissible: false,
      );
      
      // 模拟API调用
      await Future.delayed(const Duration(seconds: 2));
      
      // 创建设备对象
      final DeviceModel newDevice = DeviceModel(
        id: deviceId.value.isEmpty ? 'dev${DateTime.now().millisecondsSinceEpoch}' : deviceId.value,
        name: deviceName.value,
        type: DeviceType.fromString(deviceType.value),
        status: DeviceStatus.offline,
        createdAt: DateTime.now(),
        lastUpdatedAt: DateTime.now(),
        ownerId: 'user001',
        isEnabled: true,
        isShared: false,
        ipAddress: deviceIp.value.isEmpty ? null : deviceIp.value,
      );
      
      // 在实际应用中，这里应该调用API添加设备
      // await _deviceProvider.addDevice(newDevice);
      
      // 关闭加载指示器
      Get.back();
      
      // 显示成功消息
      _snackbarService.showSuccess('设备添加成功');
      
      // 返回设备列表页面
      Get.back();
    } catch (e) {
      // 关闭加载指示器
      Get.back();
      
      // 显示错误消息
      _snackbarService.showError('添加设备失败: $e');
    }
  }
} 